package com.huiminpay.merchant.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.merchant.api.IAppService;
import com.huiminpay.merchant.covert.AppCovert;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.mapper.AppMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class IAppServiceImpl implements IAppService {


    @Autowired
    AppMapper appMapper;


    @Override
    public AppDTO insertApp(AppDTO appDTO) throws BusinessException {
        //非空校验
        if (appDTO.getMerchantId() == null){
            throw new BusinessException(CommonErrorCode.E_300002);
        }
        if (appDTO.getAppName() == null){
            throw new BusinessException(CommonErrorCode.E_300001);
        }
        //设置应用id uuid
        appDTO.setAppId(RandomUuidUtil.getUUID());
        App app = AppCovert.INSTANCE.dto2entity(appDTO);
        appMapper.insert(app);
        appDTO.setId(app.getId());

        return appDTO;
    }

    @Override
    public AppDTO queryAppByID(String appID) throws BusinessException {
        //非空验证
        if (StringUtil.isEmpty(appID)){
            throw new BusinessException(CommonErrorCode.E_300003);
        }
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getAppId,appID);
        App app = appMapper.selectOne(qw);

        return AppCovert.INSTANCE.entity2dto(app);
    }

    @Override
    public List<AppDTO> queryApps(Long merchantId) throws BusinessException{

        //非空验证
        if (null == merchantId){
            throw new BusinessException(CommonErrorCode.E_300002);
        }
        //根据商户ID查询多个应用
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getMerchantId,merchantId);
        List<App> apps = appMapper.selectList(qw);

        return AppCovert.INSTANCE.entity2dtoList(apps);
    }
}
